<?php

namespace app\api\controller;

use app\api\model\Currency as CurrencyModel;
use app\api\model\MemberLevel as MemberLevelModel;
use app\api\server\Token;
use app\api\model\Member as MemberModel;
use app\api\model\BaseConfig as BaseConfigModel;
use app\common\model\UserMoneyLog as UserMoneyLogModel;
use think\facade\Db;
use app\common\server\Sha256 as Sha256Model;

class Login extends Baek
{

    /**
     * 登录
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function login(){

        $address =  $this->request->post('address', '', 'serach_in');
        if(empty($address)) api_error('','Parameter error',$this->language);

        if(!isValidEthereumAddress($address) && !isValidTronAddress($address)) api_error('Wallet error');

        $member = Db::name('member')->where('username',$address)->find();

        //注册用户
        if(empty($member)){
            $code =  $this->request->post('code', '', 'serach_in');
            $password =  $this->request->post('password', '', 'serach_in');
            if(empty($password)){
                api_error('','Missing password',$this->language,22);
            }
            /************* 频率限制 ************/
//            // 获取客户端IP地址
//            $client_ip = $_SERVER['REMOTE_ADDR'];
//            // 定义速率限制参数
//            $limit = 10; // 允许的请求次数
//            $window = 10; // 时间窗口（秒
//            // 获取当前IP地址的请求计数
//            $request_count = $this->redis->get("api_rate_limit:$client_ip");
//            if ($request_count === false) {
//                // 如果计数器不存在，初始化为1，并设置过期时间
//                $this->redis->set("api_rate_limit:$client_ip", 1,20);
//            } else {
//                // 如果计数器存在，递增请求计数
//                $request_count = intval($request_count);
//                if ($request_count >= $limit) {
//                    // 如果超过速率限制，返回错误或执行相应操作
//                    http_response_code(429); // HTTP 429 Too Many Requests
//                    echo "请求频率过高，请稍后再试。";
//                    exit;
//                } else {
//                    $this->redis->inc("api_rate_limit:$client_ip");
//                }
//            }
            /************* END 频率限制 ************/

            //邀请码方式
            $member_code = BaseConfigModel::config_data('member_code');

            //通过邀请码查询用户 - 通过钱包ID查询用户
            $code_member = $member_code == 1 ? MemberModel::invitation($code) : MemberModel::address($code);

            //判断该邀请码是否有效
            if(empty($code_member)) api_error('','Invalid invitation code',$this->language);

            //生成私钥
            $private_key = Sha256Model::random(65);

            Db::startTrans();
            try {
                //团队
                $team_id = $code_member['team_id'].$code_member['id'].',';
                $login_cryptosalt = Sha256Model::random(10);
                $password = md5($password.$login_cryptosalt);

                //获取矩阵位置
                $position = $this->common::downward($code_member['id']);

                //创建用户
                $mid = MemberModel::add($address,$code_member['id'],$position,$private_key,$team_id,$password,$login_cryptosalt);

                //注册奖励代币
                $register_cid = BaseConfigModel::config_data('register_cid');
                if($register_cid > 0){
                    //查询该代币
                    $currency = CurrencyModel::getDetails($register_cid);
                    //查询奖励数量
                    $register_num = BaseConfigModel::config_data('register_num');
                    if($register_num > 0 && !empty($currency)){
                        UserMoneyLogModel::change($mid,$currency['name'],$register_num,'Registration Rewards','','Registration Rewards');
                    }
                }
                //end 注册奖励代币

                //上级用户直推+1
                MemberModel::directAdd($code_member['id'],$code_member['direct']+1);

                $member['id'] = $mid;
                $level = MemberLevelModel::getDefault();
                $member['level_id'] = $level['id'];

                if(empty($mid)){
                    // 回滚事务
                    Db::rollback();
                    return api_error('','login has failed',$this->language);
                }
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return api_error('','login has failed',$this->language);
            }

        }
        //用户已存在,生成token
        $token = (new Token())->generateToken(['id'=>$member['id'],'type'=>1]);
        $level = MemberLevelModel::getDetails($member['level_id']);
        switch ($this->language){
            case 'simplified':
                $level['name'] = $level['name'];
                break;
            case 'traditional':
                $level['name'] = $level['t_name'];
                break;
            case 'english':
                $level['name'] = $level['e_name'];
                break;
        }

        return api_success(['token'=>$token,'level_name'=>$level['name']]);
    }

    /**
     * APP下载地址 和 版本号
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function downloadAPK(){
        $data['apk'] = BaseConfigModel::config_data('download_apk');
        $data['ios'] = BaseConfigModel::config_data('download_ios');
        $data['version_num'] = BaseConfigModel::config_data('version');
        $data['mailbox'] = BaseConfigModel::config_data('system_mailbox');
        return api_success($data);
    }

}